/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.tencent.tendon.convert.util;

import java.lang.reflect.Array;

/**
 * 简单的数组类， 非线程安全, 类似List
 *
 * @author nbzhang
 */
@SuppressWarnings("unchecked")
public class AnyArray<E> implements Poolable {

    protected E[] data;

    protected int size;

    public AnyArray() {
        this.data = (E[]) new Object[8];
    }

    public AnyArray(E[] data) {
        this.data = data;
    }

    protected void expand(int offset) {
        E[] newdata = (E[]) new Object[data.length + (offset > 4 ? offset : 4)];
        System.arraycopy(data, 0, newdata, 0, size);
        this.data = newdata;
    }

    public final E get(int index) {
        return this.data[index];
    }

    public final int indexOf(E e) {
        for (int i = 0; i < size; i++) {
            if (data[i] == e) return i;
        }
        return -1;
    }

    public final void add(E e) {
        if (size == data.length) expand(1);
        data[size++] = e;
    }

    public final void add(E... es) {
        if (size == data.length) expand(es.length);
        for (E e : es) {
            data[size++] = e;
        }
    }

    public final void poll() {
        if (size > 0) this.data[--size] = null;
    }

    public final E[] toArray() {
        int size0 = this.size;
        E[] data0 = this.data;
        E[] newdata = (E[]) new Object[size0];
        System.arraycopy(data0, 0, newdata, 0, size0);
        return newdata;
    }

    public final E[] toArray(final Class<E> clazz) {
        int size0 = this.size;
        E[] data0 = this.data;
        E[] newdata = (E[]) Array.newInstance(clazz, size0);
        System.arraycopy(data0, 0, newdata, 0, size0);
        return newdata;
    }

    public final int size() {
        return size;
    }

    @Override
    public void prepare() {
    }

    @Override
    public void release() {
        this.size = 0;
        this.data = (E[]) new Object[8];
    }
}
